<?php
/**
 * 用户逻辑层
 *
 */
namespace app\utils;

class DistanceUtil
{

    /**
     * 计算两点之间距离
     * @return mixed
     */
    public function getDistance(string $lat1, string $lng1, string $lat2, string $lng2)
    {
        $earthRadius = 6367000; //地球半径m

        $lat1 = ($lat1 * pi()) / 180;
        $lng1 = ($lng1 * pi()) / 180;

        $lat2 = ($lat2 * pi()) / 180;
        $lng2 = ($lng2 * pi()) / 180;

        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;

        return round($calculatedDistance);
    }

    /**
     * @param string $lat - 纬度
     * @param string $lng - 经度
     * @return bool
     * 校验经纬度合法性
     */
    public function validateLatLng(string $lat, string $lng)
    {
        if (!is_numeric($lat) || !is_numeric($lat)) {
            return false;
        }

        $latitude = (float)$lat;

        $longitude = (float)$lng;

        if ($latitude < -90 || $latitude > 90 || $longitude < -180 || $longitude > 180) {
            return false;
        }

        return true;
    }
}
